<template>
  <div>
    <h2>分类管理</h2>
    <el-card>
      <div style="margin-bottom: 16px;">
        <el-switch
            v-model="showAll"
            active-text="显示全部（含禁用）"
            inactive-text="仅显示启用"
            style="margin-right: 16px;"
            @change="fetchTree"
        />
        <el-select v-model="level" placeholder="按级别筛选" clearable style="width: 140px" @change="fetchByLevel">
          <el-option v-for="l in [1,2]" :key="l" :label="`第${l}级`" :value="l"/>
        </el-select>
        <el-button @click="resetFilter" style="margin-left: 8px;">重置</el-button>
        <el-button type="primary" @click="openAddDialog" style="margin-left: 8px;">新增分类</el-button>
      </div>
      <el-table
          :data="flatData"
          border
          style="width: 100%; margin-bottom: 16px;"
          @row-click="handleRowClick"
      >
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="parentId" label="父ID" width="80"/>
        <el-table-column prop="level" label="级别" width="80"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click.stop="handleRowClick(scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click.stop="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="detailDialog" title="分类详情" width="400px">
        <el-descriptions :column="1" border v-if="detail">
          <el-descriptions-item label="ID">{{ detail.id }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{ detail.name }}</el-descriptions-item>
          <el-descriptions-item label="父ID">{{ detail.parentId }}</el-descriptions-item>
          <el-descriptions-item label="级别">{{ detail.level }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="detail.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
        </el-descriptions>
        <template #footer>
          <el-button @click="detailDialog = false">关闭</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="editDialog" :title="editMode ? '编辑分类' : '新增分类'" width="400px">
        <el-form :model="editForm" label-width="80px">
          <el-form-item label="名称">
            <el-input v-model="editForm.name"/>
          </el-form-item>
          <el-form-item label="父ID">
            <el-input v-model="editForm.parentId" type="number"/>
          </el-form-item>
          <el-form-item label="级别">
            <el-input v-model="editForm.level" type="number"/>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="editForm.sort" type="number"/>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="editForm.status">
              <el-option :value="1" label="启用"/>
              <el-option :value="0" label="禁用"/>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialog = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">{{ editMode ? '保存' : '新增' }}</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {
  getCategoryTree,
  getAllCategoryTree,
  getCategoryById,
  getCategoriesByLevel,
  addCategory, updateCategory, deleteCategory
} from '../api/category'
import {ElMessage} from 'element-plus'

const editDialog = ref(false)
const editMode = ref(false) // false: 新增, true: 编辑
const editForm = reactive({
  id: null,
  name: '',
  parentId: 0,
  level: 1,
  sort: 0,
  status: 1
})

function openAddDialog() {
  editMode.value = false
  Object.assign(editForm, {id: null, name: '', parentId: 0, level: 1, sort: 0, status: 1})
  editDialog.value = true
}

function openEditDialog(row) {
  editMode.value = true
  Object.assign(editForm, row)
  editDialog.value = true
}

async function submitEdit() {
  if (editMode.value) {
    await updateCategory(editForm.id, editForm)
  } else {
    await addCategory(editForm)
  }
  editDialog.value = false
  fetchTree()
}

async function handleDelete(row) {
  if (confirm('确定要删除该分类吗？')) {
    await deleteCategory(row.id)
    fetchTree()
  }
}


const rawData = ref([])
const flatData = ref([])
const showAll = ref(false)
const level = ref()
const detailDialog = ref(false)
const detail = ref(null)

const flatten = (tree, arr = []) => {
  tree.forEach(item => {
    arr.push(item)
    if (item.children && item.children.length) {
      flatten(item.children, arr)
    }
  })
  return arr
}

const fetchTree = async () => {
  try {
    let res
    if (showAll.value) {
      res = await getAllCategoryTree()
    } else {
      res = await getCategoryTree()
    }
    rawData.value = res.data || []
    flatData.value = flatten(rawData.value)
  } catch (e) {
    ElMessage.error('获取分类树失败')
  }
}

const fetchByLevel = async () => {
  if (!level.value) {
    fetchTree()
    return
  }
  try {
    const res = await getCategoriesByLevel(level.value)
    rawData.value = res.data || []
    flatData.value = flatten(rawData.value)
  } catch (e) {
    ElMessage.error('按级别获取分类失败')
  }
}

const resetFilter = () => {
  showAll.value = false
  level.value = undefined
  fetchTree()
}

const handleRowClick = async (data) => {
  try {
    const res = await getCategoryById(data.id)
    if (res.data) {
      detail.value = res.data
      detailDialog.value = true
    }
  } catch (e) {
    ElMessage.error('获取分类详情失败')
  }
}

fetchTree()
</script>